#!/bin/bash
#使用openssl创建私钥公钥
DAEMON=kuboard.local.com
#创建私有证书目录
CERT_PATH=/data/cert
#指定应用的名称
APPNAME=harbor

mkdir -p ${CERT_PATH}
cd ${CERT_PATH}

openssl genrsa -out ca.key 4096
openssl req -x509 -new -nodes -sha512 -days 3650 -subj "/C=CN/ST=Beijing/L=Beijing/O=example/OU=Personal/CN=${DAEMON}" -key ca.key -out ca.crt
openssl genrsa -out ${DAEMON}.key 4096
openssl req -sha512 -new -subj "/C=CN/ST=Beijing/L=Beijing/O=example/OU=Personal/CN=${DAEMON}" -key ${DAEMON}.key -out ${DAEMON}.csr

cat > v3.ext <<-EOF
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
extendedKeyUsage = serverAuth
subjectAltName = @alt_names

[alt_names]
DNS.1=local.com
IP.1=192.168.56.8
IP.2=192.168.56.40
IP.3=192.168.56.41
EOF

openssl x509 -req -sha512 -days 3650 -extfile v3.ext -CA ca.crt -CAkey ca.key -CAcreateserial -in ${DAEMON}.csr -out ${DAEMON}.crt
openssl x509 -inform PEM -in ${DAEMON}.crt -out ${DAEMON}.cert
cp ${DAEMON}.crt /etc/pki/ca-trust/source/anchors/${DAEMON}.crt
update-ca-trust
#### 配置docker信任证书
# 
cd ${CERT_PATH}
mkdir -p /etc/docker/certs.d/${DAEMON}/
cp ${DAEMON}.cert /etc/docker/certs.d/${DAEMON}/
cp ${DAEMON}.key /etc/docker/certs.d/${DAEMON}/
cp ca.crt /etc/docker/certs.d/${DAEMON}/

### 将生成的证书放到指定的应用目录下
# 比如 /data/harbor/ssl/ 目录
mkdir -p /data/${APPNAME}/ssl
cp ${DAEMON}.key /data/${APPNAME}/ssl/${DAEMON}.key
cp ${DAEMON}.crt /data/${APPNAME}/ssl/${DAEMON}.crt